package handler

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"seckill-system/model"
	"seckill-system/util"
	"strconv"
)

type GiftHandler struct {
	giftDAO model.GormGiftDAO
	inventDAO model.GormInventoryDAO
}

func NewGiftHandler(giftDAO model.GormGiftDAO, inventDAO model.GormInventoryDAO) *GiftHandler {
	return &GiftHandler{
		giftDAO: giftDAO,
		inventDAO: inventDAO,
	}
}

// 获取所有奖品信息，用于初始化轮盘
func (h *GiftHandler) GetAllGifts(ctx *gin.Context) {
	gifts:=h.giftDAO.GetAllGifts(ctx)
	if len(gifts)==0 {
		ctx.JSON(http.StatusInternalServerError, nil)
		return
	}
	// 抹除敏感信息，用于返给前端
	for _, gift := range gifts {
		gift.Number = 0
	}
	fmt.Println(len(gifts))
	fmt.Println(gifts)
	ctx.JSON(http.StatusOK, gifts)
}

func (h *GiftHandler) Lottery(ctx *gin.Context) {
	for try:=0; try<10; try++ {
		gifts:=h.giftDAO.GetAllGiftsInventory(ctx)
		ids:=make([]int, 0, len(gifts))
		probs:=make([]float64, 0, len(gifts))
		for _, gift := range gifts {
			if gift.Number > 0 {
				ids = append(ids, gift.Id)
				probs = append(probs, float64(gift.Number))
			}
		}
		if len(ids)== 0 {
			ctx.String(http.StatusOK, strconv.Itoa(0))
			return
		}
		index:=util.Lottery(probs)
		giftId:=ids[index]
		err:=h.inventDAO.ReduceInventory(giftId)
		if err!=nil{
			util.LogRus.Warnf("奖品%d减库存失败", giftId)
			continue
		} else {
			ctx.String(http.StatusOK, strconv.Itoa(giftId))
			return
		}
	}
	ctx.String(http.StatusOK, strconv.Itoa(model.EMPTY_GIFT))	//10次之后返回谢谢参与
}
